package cn.itcast.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @Author: LDeng
 * @Date: 2021-05-17 14:08
 */
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        //1, 启动类
        ChannelFuture channelFuture = new Bootstrap()
                //2，添加EventLoop
                .group(group)
                //3, 选择客户端channel实现
                .channel(NioSocketChannel.class)
                .handler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override//在连接建立后才会被调用
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                                ch.pipeline().addLast(new StringEncoder());
                            }
                        })
                //1,connect异步非阻塞， main发起调用，真正执行connect是nio线程
                .connect(new InetSocketAddress("localhost", 8080));
        /**
         * 同步处理连接结果 sync()方法
         */
        Channel channel = channelFuture.sync().channel();//调用channelFuture的sync()方法后， 主线程就不会无阻塞向下执行
                                                        //直到nio线程建立完毕， 主线程才会继续向下执行
        /**
         * 异步添加linstner来监听,
         * 主线程传递回调对象给nio线程，nio线程建立好连接后会调用回调对象的operationComplete() 方法


        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                 //nio线程连接建立好以后会调用operationComplete方法
                Channel channel = future.channel();
                //===> 继续执行业务， 但是线程已经变成nio线程
            }
        });
         */

        log.debug("{}",channel);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while(true){//不断接受
                String line = scanner.nextLine();
                if("q".equals(line)){
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"input").start();

        //获取ClosedFuture对象，channel关闭以后的操作 1， 同步  2， 异步
        ChannelFuture closeFuture = channel.closeFuture();
        log.debug("waiting close.....");//上面的新线程中输入了q，调用了channel.close方法后才向下执行，否则阻塞
        closeFuture.sync();
        log.debug("channel关闭后的操作 ---主线程");
        group.shutdownGracefully();

//       closeFuture.addListener(new ChannelFutureListener() {
//           @Override
//           public void operationComplete(ChannelFuture future) throws Exception {
//               log.debug("channel关闭后的操作 ---nio线程");//异步， nio线程调用
//               group.shutdownGracefully();
//           }
//       });
    }
}
